/**
 * fileName: YLES_CLIENT_TOOL
 * @NApiVersion 2.1
 */
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() { return m[k]; } };
    }
    Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
    __setModuleDefault(result, mod);
    return result;
};
define(["require", "exports", "N/currentRecord", "N/search", "N/runtime", "./papaparse"], function (require, exports, crd, search, runtime, Papa) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.initCheckCSVProgress = exports.initCSVProgress = exports.addScreenDisabled = exports.exportMyCSV = exports.markMyAll = exports.changeURLArg = exports.changePageNo = exports.changeMyPageIndex = void 0;
    Papa = __importStar(Papa);
    const subInfo = { sublistId: 'info_list' };
    /**
     *  更改页数
     *  @param num - 跳转的页数（基于当前界面 +n -n）
     */
    function changeMyPageIndex(num) {
        const rec = crd.get();
        const nowPage = rec.getValue('current_page');
        let url = window.location.href;
        url = changeURLArg(url, 'nowPage', nowPage + num);
        window.onbeforeunload = null;
        window.location.href = url;
    }
    exports.changeMyPageIndex = changeMyPageIndex;
    /**
     * 更改每页显示行数
     * @param rec - 当前记录
     */
    function changePageNo(rec) {
        const pageNo = rec.getValue('lines_page');
        let url = window.location.href;
        url = changeURLArg(url, 'pageNo', pageNo);
        url = changeURLArg(url, 'nowPage', 1);
        window.onbeforeunload = null;
        window.location.href = url;
    }
    exports.changePageNo = changePageNo;
    //替换链接中的值
    function changeURLArg(targetUrl, arg, arg_val) {
        let pattern = arg + '=([^&]*)';
        let replaceText = arg + '=' + arg_val;
        if (targetUrl.match(pattern)) {
            let tmp = '/(' + arg + '=)([^&]*)/gi';
            tmp = targetUrl.replace(eval(tmp), replaceText);
            return tmp;
        }
        else {
            if (targetUrl.match('[\?]')) {
                return targetUrl + '&' + replaceText;
            }
            else {
                return targetUrl + '?' + replaceText;
            }
        }
    }
    exports.changeURLArg = changeURLArg;
    /**
     * 界面选择按钮
     * @param num - 是否限制行数
     * @param val - 勾选或者不勾选
     */
    function markMyAll(val, num) {
        const rec = crd.get();
        const cnt = rec.getLineCount(Object.assign({}, subInfo));
        for (let i = 0; i < cnt; i++) {
            if (num && i >= num)
                return;
            rec.selectLine(Object.assign(Object.assign({}, subInfo), { line: i }));
            rec.setCurrentSublistValue(Object.assign(Object.assign({}, subInfo), { fieldId: 'line_check', value: val }));
            rec.commitLine(Object.assign({}, subInfo));
        }
    }
    exports.markMyAll = markMyAll;
    //依据界面信息下载导出CSV
    function exportMyCSV() {
        const curRec = crd.get();
        const sublist_fields = JSON.parse(curRec.getValue({ fieldId: 'sublist_fields' }));
        const cnt = curRec.getLineCount(Object.assign({}, subInfo));
        const csvData = [];
        for (let i = 0; i < cnt; i++) {
            const dd = {};
            sublist_fields.map(function (sf) {
                let vv = curRec.getSublistValue(Object.assign(Object.assign({}, subInfo), { fieldId: sf.id, line: i })) || '';
                vv = String(vv).replace(/<\/{0,1}p>/g, '');
                dd[sf.label] = vv;
            });
            // if(fail || dd.msg == 'This item have been inactived.'){
            csvData.push(dd);
            // }
        }
        const fields = sublist_fields.map(function (sf) {
            return sf.label;
        });
        const csv_content = Papa.unparse(csvData, { columns: fields });
        exeDownLoad(csv_content, 'export_data.csv');
    }
    exports.exportMyCSV = exportMyCSV;
    //执行下载
    function exeDownLoad(content, fileName) {
        const data = "\ufeff" + content;
        const aEle = document.createElement("a"); // 创建a标签
        const blob = new Blob([data], { type: 'text/csv,charset=UTF-8' });
        aEle.download = fileName; // 设置下载文件的文件名
        aEle.href = URL.createObjectURL(blob);
        aEle.click(); // 设置点击事件
    }
    let bartimer = 0;
    //添加屏幕遮罩，黑屏
    function addScreenDisabled() {
        var $ = jQuery;
        var docHeight = $(document).height(); //获取窗口高度
        $('body').append('<div id="overlay"></div>');
        $('#overlay').append(`
        <div id="screen_ck_id" style="width:100%;height:100%;line-height:700px;text-align:center;display:block;font-weight: bold; color: red">
             文件校验中，请勿刷新界面...
        </div>`);
        $('#overlay')
            .height(docHeight)
            .css({
            'opacity': .6,
            'position': 'absolute',
            'top': 0,
            'left': 0,
            'background-color': '#939090',
            'width': '100%',
            'z-index': 10000 //保证这个悬浮层位于其它内容之上
        });
        //initProgress();
        //window.location.reload();
        // setTimeout(function(){$('#overlay').fadeOut('slow')}, 10000000);
    }
    exports.addScreenDisabled = addScreenDisabled;
    //启动导入进度条
    function initCSVProgress() {
        //清除所有定时器
        if (bartimer > 0) {
            clearInterval(bartimer);
        }
        //重新启用定时器
        bartimer = window.setInterval(function () { setProcess(); }, 2000);
        function setProcess() {
            try {
                let logSts = '3', dealNos = 0;
                const crd = require("N/currentRecord");
                const search = require("N/search");
                const cur_rec = crd.get();
                const logId = String(cur_rec.getValue('import_log_id'));
                const totalNum = Number(cur_rec.getValue('ck_success_line'));
                //获取导入的数据条数
                const ckiSearch = search.create({
                    type: 'customrecord_lyes_head_item_barcode',
                    filters: [
                        ['custrecord_yles_import_log', 'anyof', logId]
                    ],
                    columns: [
                        { name: 'custrecord_yles_status', join: 'custrecord_yles_import_log', summary: search.Summary.GROUP, sort: search.Sort.ASC },
                        { name: 'id', join: 'custrecord_yles_head', summary: search.Summary.COUNT },
                    ]
                });
                const data = ckiSearch.run().getRange({ start: 0, end: 1 });
                if (data && data.length > 0) {
                    logSts = data[0].getValue(ckiSearch.columns[0]);
                    dealNos = Number(data[0].getValue(ckiSearch.columns[1]));
                }
                if (logSts == '3') {
                    logSts = search.lookupFields({
                        type: 'customrecord_yles_import_csv_log',
                        id: logId,
                        columns: ['custrecord_yles_status']
                    })['custrecord_yles_status'][0].value;
                }
                // console.log('logSts',logSts);
                // console.log('dealNos',dealNos);
                // console.log('totalNum',totalNum);
                //导入中才显示进度条
                if (logSts == '3') {
                    const percent = dealNos / totalNum;
                    if (percent <= 0) {
                        /*// @ts-ignore
                        jQuery('#import_csv_progress').LineProgressbar({
                            percentage: 0,
                            fillBackgroundColor: '#e67e22',
                            height: '25px',
                            radius: '15px'
                        });*/
                    }
                    else if (percent < 0.5) {
                        // @ts-ignore
                        jQuery('#import_csv_progress').LineProgressbar({
                            percentage: percent * 100,
                            fillBackgroundColor: '#e67e22',
                            height: '25px',
                            radius: '15px'
                        });
                    }
                    else if (percent < 0.8) {
                        // @ts-ignore
                        jQuery('#import_csv_progress').LineProgressbar({
                            percentage: percent * 100,
                            fillBackgroundColor: '#1abc9c',
                            height: '25px',
                            radius: '15px'
                        });
                    }
                    else if (percent <= 0.99) {
                        // @ts-ignore
                        jQuery('#import_csv_progress').LineProgressbar({
                            percentage: percent * 100,
                            fillBackgroundColor: '#1abc9c',
                            height: '25px',
                            radius: '15px'
                        });
                        // window.clearInterval(bartimer);
                    }
                }
                else {
                    // @ts-ignore
                    jQuery('#import_csv_progress').LineProgressbar({
                        percentage: 100,
                        fillBackgroundColor: '#1abc9c',
                        height: '25px',
                        radius: '15px'
                    });
                    window.onbeforeunload = null;
                    window.clearInterval(bartimer);
                    window.location.reload();
                }
            }
            catch (erxp) {
                console.log('setProcess', erxp);
                //@ts-ignore
                if (erxp.name == 'SCRIPT_EXECUTION_USAGE_LIMIT_EXCEEDED') {
                    window.onbeforeunload = null;
                    window.clearInterval(bartimer);
                    window.location.reload();
                }
            }
        }
    }
    exports.initCSVProgress = initCSVProgress;
    //启动导入进度条
    function initCheckCSVProgress() {
        //清除所有定时器
        if (bartimer > 0) {
            clearInterval(bartimer);
        }
        //重新启用定时器
        bartimer = window.setInterval(function () { setProcess(); }, 3000);
        function setProcess() {
            try {
                let logSts = '2';
                const runtime = require("N/runtime");
                const search = require("N/search");
                const cur_rec = crd.get();
                const logId = cur_rec.getValue('import_log_id');
                const totalNum = Number(cur_rec.getValue('total_line'));
                const ckd_line = cur_rec.getValue('ckd_line');
                const logInfos = search.lookupFields({
                    type: 'customrecord_yles_import_csv_log',
                    id: logId,
                    columns: ['custrecord_yles_status', 'custrecord_yles_ckd_line_no']
                });
                const dealNos = logInfos['custrecord_yles_ckd_line_no'];
                logSts = logInfos['custrecord_yles_status'][0].value;
                //校验中才显示进度条
                if (logSts == '2') {
                    const percent = dealNos / totalNum;
                    // console.log('percent',percent);
                    if (percent <= 0) {
                        /*// @ts-ignore
                        jQuery('#import_csv_progress').LineProgressbar({
                            percentage: 0,
                            fillBackgroundColor: '#e67e22',
                            height: '25px',
                            radius: '15px'
                        });*/
                    }
                    else if (percent < 0.5) {
                        // @ts-ignore
                        jQuery('#check_csv_progress').LineProgressbar({
                            percentage: percent * 100,
                            fillBackgroundColor: '#e67e22',
                            height: '25px',
                            radius: '15px'
                        });
                    }
                    else if (percent < 0.8) {
                        // @ts-ignore
                        jQuery('#check_csv_progress').LineProgressbar({
                            percentage: percent * 100,
                            fillBackgroundColor: '#1abc9c',
                            height: '25px',
                            radius: '15px'
                        });
                    }
                    else if (percent <= 0.99) {
                        // @ts-ignore
                        jQuery('#check_csv_progress').LineProgressbar({
                            percentage: percent * 100,
                            fillBackgroundColor: '#1abc9c',
                            height: '25px',
                            radius: '15px'
                        });
                        // window.clearInterval(bartimer);
                    }
                }
                else {
                    // @ts-ignore
                    jQuery('#check_csv_progress').LineProgressbar({
                        percentage: 100,
                        fillBackgroundColor: '#1abc9c',
                        height: '25px',
                        radius: '15px'
                    });
                    window.onbeforeunload = null;
                    window.clearInterval(bartimer);
                    window.location.reload();
                }
            }
            catch (erxp) {
                console.log('setProcess', erxp);
                //@ts-ignore
                if (erxp.name == 'SCRIPT_EXECUTION_USAGE_LIMIT_EXCEEDED') {
                    window.onbeforeunload = null;
                    window.clearInterval(bartimer);
                    window.location.reload();
                }
            }
        }
    }
    exports.initCheckCSVProgress = initCheckCSVProgress;
    function todoTest() {
        search.load({ id: '' });
        runtime.getCurrentUser().id;
    }
});
